package storage

import (
	"errors"
	"fmt"
	"github.com/gookit/goutil/fsutil"
	"xiuxian_help_tool/backend/model"
)

// GetCardFileList 获取卡片文件列表
func (d *Storage) GetCardFileList() ([]*model.CardInfoFile, error) {
	l := d.orm.CardInfoFile
	return l.Find()
}

// DeleteCardFile 删除卡片文件
func (d *Storage) DeleteCardFile(id int) error {
	l := d.orm.CardInfoFile
	result, err := l.Where(l.ID.Eq(id)).Delete()
	if err != nil {
		d.log.Fatal(err)
		return err
	}
	d.log.Println(fmt.Sprintf("delete %d files", result.RowsAffected))
	return nil
}

// AddCardFile 添加卡片文件
func (d *Storage) AddCardFile(path string) error {

	if !fsutil.FileExists(path) {
		return errors.New("file not exist")
	}
	entity := model.CardInfoFile{
		FileName: fsutil.PathName(path),
		FilePath: path,
	}
	err := d.orm.CardInfoFile.Create(&entity)
	if err != nil {
		return err
	}
	d.log.Println(fmt.Sprintf("add card file %s", path))
	return nil
}

// FindCardFile 获取卡片文件
func (d *Storage) FindCardFile(id int) (*model.CardInfoFile, error) {
	l := d.orm.CardInfoFile
	return l.Where(l.ID.Eq(id)).First()
}
